const g = require('global');
const { Board } = require('blockControl');
cc.Class({
    extends: cc.Component,

    properties: {
        canvas: cc.Node,
        board: {
            type: cc.Node,
            default: null,
        },
        scoreLabel: {
            type: cc.Label,
            default: null,
        },
        iconPrefab: {
            type: cc.Prefab,
            default: null,
        },
    },

    // game function
    initGameData: function() {
        this.score = 0;
        this.boardCtrl = new Board(640, 750, 7,8);
    },
    // 触摸开始
    onTouchBegin: function (event) {
        // cc.log('touch start');
        const touches = event.getTouches();
        const touchLoc = touches[0].getLocation();
        // 遍历每个方块，检查方块是否被移动
        this.boardCtrl.touchStart(touchLoc);
    },

    onTouchMove: function (event) {
        // cc.log('touch move');
        const touches = event.getTouches();
        const touchLoc = touches[0].getLocation();
        const startTouchLoc = touches[0].getStartLocation();
        const deltaX = touchLoc.x - startTouchLoc.x;
        const deltaY = touchLoc.y - startTouchLoc.y;
        // 获得点击方向
        const direct = this.getTouchDirect(deltaX, deltaY);
        this.boardCtrl.moving(direct, touchLoc, deltaX, deltaY);

    },

    onTouchEnd: function(event) {
        // cc.log('touch end');
        const touches = event.getTouches();
        const touchLoc = touches[0].getLocation();
        const startTouchLoc = touches[0].getStartLocation();
        const deltaX = touchLoc.x - startTouchLoc.x;
        const deltaY = touchLoc.y - startTouchLoc.y;
        // 获得点击方向
        const direct = this.getTouchDirect(deltaX, deltaY);
        this.boardCtrl.moveEnd(direct, touchLoc)
    },

    // LIFE-CYCLE CALLBACKS:

    onLoad: function () {
        // init data
        this.initGameData();
        // 初始化棋盘
        this.boardCtrl.init(this.iconPrefab, this.board);

        // 触摸事件
        this.canvas.on(cc.Node.EventType.TOUCH_START, this.onTouchBegin, this);
        this.canvas.on(cc.Node.EventType.TOUCH_MOVE, this.onTouchMove, this);
        this.canvas.on(cc.Node.EventType.TOUCH_END, this.onTouchEnd, this);
        this.canvas.on(cc.Node.EventType.TOUCH_CANCEL, this.onTouchEnd, this);
    },

    start () {
    },

    // update (dt) {},

    // 获得点击方向
    getTouchDirect: function (deltaX, deltaY) {
        let anchor;
        const deltaX2 = deltaX*deltaX;
        const deltaY2 = deltaY*deltaY;
        // 左右移动
        if(deltaX2 > deltaY2) {
            if(deltaX<0) {
                // 向左
                anchor = g.direct.left;
            } else {
                // 向右
                anchor = g.direct.right;
            }
        } else {
            // 上下移动
            if(deltaY>0) {
                // 上
                anchor = g.direct.up;
            } else {
                anchor = g.direct.down;
            }
        }
        return anchor;
    },
});
